//
//  WBComposePictureView.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/9.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit
import SVProgressHUD

private let WBComposePictureViewCellid = "WBComposePictureViewCellid"
class WBComposePictureView: UICollectionView {
    //加号 cell 点击执行的闭包
    var addClosure:(()->())?
    lazy var pictures:[UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        self.setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setUI(){
        self.register(WBComposePictureViewCell.self, forCellWithReuseIdentifier: WBComposePictureViewCellid)
        self.dataSource = self
        self.delegate = self
    }
    func addImage(image:UIImage){
        if pictures.count < 9 {
            pictures.append(image)
            reloadData()
        }
        else
        {
            SVProgressHUD.showError(withStatus: "图片数量超出限制")
        }
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let itemMargin: CGFloat = 5
        let itemWH = (self.frame.width - 2 * itemMargin) / 3
        
        // 获取到布局对象，设置条目的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin

    }
}
extension WBComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //print("dianji")
        collectionView.deselectItem(at: indexPath, animated: true)
        if indexPath.item == pictures.count{
            addClosure?()
        }
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //return 9
        //return pictures.count
        return (pictures.count == 0 || pictures.count == 9) ? pictures.count : pictures.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.dequeueReusableCell(withReuseIdentifier: WBComposePictureViewCellid, for: indexPath) as! WBComposePictureViewCell
        //cell.backgroundColor = RandomColor
        if indexPath.item < pictures.count
        {
            let image = pictures[indexPath.item]
            cell.image = image
        }else{
            cell.image = nil
        }
        cell.deleteClosure = {[weak self] in
            //点击删除按钮，删除对应位置的图片
            self?.pictures.remove(at: indexPath.item)
            //print(indexPath.item)
            self?.reloadData()
        }
        return cell
    }
}

class  WBComposePictureViewCell: UICollectionViewCell {
    //删除按钮闭包
    var deleteClosure: (()->())?
    var image:UIImage?
    {
        didSet{
            if image == nil{
                imgView.image = #imageLiteral(resourceName: "compose_pic_add")
                imgView.highlightedImage = #imageLiteral(resourceName: "compose_pic_add_highlighted")
            }else
            {
                imgView.image = image
            }
            deleteButton.isHidden = image == nil
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc private func deleteButtonClikc(){
        //print("删除按钮点击了")
        //执行闭包
        deleteClosure?()
    }
    private func setUI()
    {
        contentView.addSubview(imgView)
        contentView.addSubview(deleteButton)
        imgView.snp_makeConstraints { (make)->Void in
            make.edges.equalTo(contentView)
        }
        deleteButton.snp_makeConstraints { (make)->Void in
            make.top.right.equalTo(contentView)
        }
    }
    //懒加载控件
    lazy var imgView:UIImageView = {
        let imgV = UIImageView()
        imgV.contentMode = .scaleAspectFill
        imgV.clipsToBounds = true
        return imgV
    }()
    lazy var deleteButton:UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(deleteButtonClikc), for: UIControlEvents.touchUpInside)
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: UIControlState.normal)
        return btn
    }()
}
